/**
 * 登陆请求数据包装
 * 2018-04-26
 * kairo
 */
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 7000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (config.method === 'post') {
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    config.data = qs.stringify({
      ...config.data
    })
  }
  if (store.getters.login_token) {
    config.headers['token'] = store.getters.login_token // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['mobile'] = store.getters.login_mobile
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    /**
      * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
      * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
      */
    const res = response.data
    if (res.code !== 0) {
      // 999:其他客户端登录了;
      if (res.code === -9998 || res.code === 999) {
        if (res.code === 999) {
          Message({
            message: res.msg,
            type: 'error'
          })
        } else {
          Message({
            message: '你已被列入黑名单,请先联系管理员~~',
            type: 'error',
            showClose: true
          })
        }
        setTimeout(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        }, 500)
      } else {
        Message({
          message: res.msg,
          type: 'error',
          showClose: true
        })
      }
    }
    return response
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      showClose: true
    })
    return Promise.reject(error)
  })

export default service
